
package stcu;

import com.nvlled.route.*;
import stcu.robjects.*;
import java.util.*;
import java.net.*;

public class DefaultGroup extends Group implements ObjectReceiver<GroupCreate> {

    public static final int DEFAULT_ID = 0;

    private ServerAuth auth;
    private IDGenerator idGen;
    private List<GroupInfo> groupDirectory;

    public DefaultGroup(final ObjectRouter router, ServerAuth auth) {
        super(router, DEFAULT_ID+"", auth.getAccount(), true);
        this.auth = auth;
        idGen = new IDGenerator(DEFAULT_ID+1);
        groupDirectory = new ArrayList<GroupInfo>();

        router.subscribe(GroupCreate.class, this);
        router.subscribe(GroupList.class, new ObjectReceiver<GroupList>() {
            public void receive(GroupList request) {
                for (GroupInfo info: groupDirectory) {
                    GroupAdd groupAdd = new GroupAdd(info.getId(),
                        info.getAddress(),
                        info.getTitle(),
                        info.getName());

                    router.deliver(groupAdd, request.getSourceAddress());
                }
            }
        });
        auth.setDefaultGroup(this);
    }

    @Override
    public boolean isAllowed(String name) {
        return auth.isLoggedIn(name);
    }

    public void deleteAuthoredGroups(String creator) {
        Set<String> users = auth.getLoggedUsers();
        for (GroupInfo info: new ArrayList<GroupInfo>(groupDirectory)) {
            if (info.getIDNumber().equals(creator)) {
                groupDirectory.remove(info);
                router.deliver(new GroupDel(info.getId(), 
                            info.getTitle(),
                            info.getName()), users);
            }
        }
    }

    public void receive(GroupCreate request) {
        AddressTable table = router.getTable();
        SocketAddress source = request.getSourceAddress();
        String name = table.getName(source);

        String groupId = idGen.nextId()+"";

        if (!isAllowed(name)) {
            router.deliver(new GroupCreate.Status("denied", groupId), source);
            return;
        } 

        GroupInfo info = new GroupInfo(groupId, request);
        groupDirectory.add(info);
        router.deliver(new GroupCreate.Status(request.getId(), "ok", groupId), source);
        notifyMembers(info);
    }

    private void notifyMembers(GroupInfo info) {
        AddressTable table = router.getTable();
        GroupAdd groupAdd = 
            new GroupAdd(info.getId(),
                    info.getAddress(),
                    info.getTitle(),
                    info.getName());

        for (MemberAdd member: members.values()) {
            String idNumber = member.getIDNumber();
            //SocketAddress address = table.getAddress(idNumber);
            SocketAddress address = member.getAddress();
            router.deliver(groupAdd, idNumber);
        }
    }
} 

